﻿using JetBrains.Annotations;
using Dyn.News.Models;
using Dyn.News.Extensions;
using Orchard.ContentManagement.Drivers;
using Orchard.Core.Feeds;
using System.Collections.Generic;
using Orchard.ContentManagement;
using System;

namespace Dyn.News.Drivers {
    [UsedImplicitly]
    public class ArticlePartDriver : ContentPartDriver<ArticlePart> {
        private readonly IFeedManager _feedManager;

        public ArticlePartDriver(IFeedManager feedManager) {
            _feedManager = feedManager;
        }

        protected override DriverResult Display(ArticlePart part, string displayType, dynamic shapeHelper)
        {
            if (displayType.StartsWith("Detail"))
                _feedManager.Register(part.CategoryPart);

            return null;


        }
        protected override DriverResult Editor(ArticlePart part, dynamic shapeHelper)
        {
            var results = new List<DriverResult> {
                ContentShape("Parts_Category_Article_Fields",
                             () => shapeHelper.EditorTemplate(TemplateName: "Parts.Category.Article.Fields", Model: part, Prefix: Prefix)),
            };
            if (part.Id > 0)
                results.Add(ContentShape("Category_DeleteButton",
                    deleteButton => deleteButton));

            return Combined(results.ToArray());
        }
        protected override DriverResult Editor(ArticlePart CategoryPart, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(CategoryPart, Prefix, null, null);
            return Editor(CategoryPart, shapeHelper);
        }
        protected override void Importing(ArticlePart part, Orchard.ContentManagement.Handlers.ImportContentContext context)
        {
            var description = context.Attribute(part.PartDefinition.Name, "Sumary");
            if (description != null)
            {
                part.Sumary = description;
            }
            var author = context.Attribute(part.PartDefinition.Name, "Author");
            if (author != null)
            {
                part.Author = author;
            }

            var postCount = context.Attribute(part.PartDefinition.Name, "Visited");
            if (postCount != null)
            {
                part.Visited = Convert.ToInt32(postCount);
            }
            else
                part.Visited = 0;
        }

        protected override void Exporting(ArticlePart part, Orchard.ContentManagement.Handlers.ExportContentContext context)
        {
            context.Element(part.PartDefinition.Name).SetAttributeValue("Sumary", part.Sumary);
            context.Element(part.PartDefinition.Name).SetAttributeValue("Author", part.Author);
            context.Element(part.PartDefinition.Name).SetAttributeValue("Visited", part.Visited);
        }
    }
}